import util from './util';
// import commonFunction from '@/utils/commonFunction.js'
import md5 from './md5';
import tip from './tip'
// import matomo from 'wechat-matomo';
// import EFSTracking from './efs-tracking'
import api from '@/api/api';
const API_SECRET_KEY = 'www.mall.cycle.com';
const TIMESTAMP = util.getCurrentTime();
const SIGN = md5.hex_md5((TIMESTAMP + API_SECRET_KEY).toLowerCase());
const GATEWAYIDJSON = {
  formal: 'efc-sg-prod-9g2vqh1q007068d1',
  trial: 'efc-sg-test-tke-8gsfog1ydae06fe0'
}
let merchantInfo = uni.getStorageSync('merchantInfo') || "";
const accountInfo = uni.getAccountInfoSync()
let appId = accountInfo.miniProgram.appId || "wx158a61365a8c8fd6"
let loadTime
let pageUrl = ''
let currentUrl = '';
/**
 * 拼接对象为请求字符串
 * @param {Object} obj - 待拼接的对象
 * @returns {string} - 拼接成的请求字符串
 * Auth:WANGJIAN
 */
const encodeSearchParams = (obj) => {
  const params = []

  Object.keys(obj).forEach((key) => {
    let value = obj[key]
    // 如果值为undefined我们将其置空
    if (typeof value === 'undefined') {
      value = ''
    }
    // 对于需要编码的文本（比如说中文）我们要进行编码
    params.push([key, encodeURIComponent(value)].join('='))
  })

  return params.join('&')
}

const wxRequest = async (params = {}, baseUrl, serviceUrl, apiKey, path, show_loading = false) => {
  return new Promise(async (resolve, reject) => {
    const baseUrlRequest = accountInfo.miniProgram.envVersion == 'release' || api.environment == "formal" ? "https://api.cloud.efashionchina.com" : "https://macallan.morefun.me"
    let host = baseUrlRequest.substring(8)
    let url = serviceUrl + path
    if (url != '') {
      clearTimeout(loadTime)
      if (show_loading) {
        loadTime = setTimeout(() => {
          tip.loading();
        }, 500)
      }
      let data = params.query || {};
      let headers = params.header || {};
      if (!!apiKey) {
        headers['X-Api-Key'] = apiKey
      }
      headers['appId'] = appId
      if(api.environment == "formal") {
        headers['X-WX-EXCLUDE-CREDENTIALS'] = 'unionid, cloudbase-access-token, openid'
        headers['X-WX-GATEWAY-ID'] = GATEWAYIDJSON[api.environment]
        headers['HOST'] = host
        if (url.search('efashionchina') === -1) {
          data.sign = SIGN;
          data.time = TIMESTAMP;
        }
        const startTime = Date.now();
        if(!!params.method && params.method != "GET") {
          wx.cloud.callContainer({
            path: url, // 透传到后台服务
            header: headers,
            method: params.method || 'GET',
            data: data,
          }).then((res) => {
            if (show_loading) {
              tip.loaded();
              clearTimeout(loadTime)
            }
            if (url.indexOf('cloud-sales-order/customer/sales_order') !== -1 && params.method == 'POST') {
              if (res.statusCode == 500 || res.statusCode == 504) {
                uni.redirectTo({
                  url: '/pages/util/error'
                });
              }
            }
            if (res.statusCode == 429) {
              // tip.plainText('您动作太快，请慢点哟～', 2000)
							resolve({msg: "您动作太快，请慢点哟～", type:'showToast'})
            }else if (res && res.errMsg == "request:fail timeout") {
              // tip.plainText('网络状态不佳，请重试')
							resolve({msg: "网络状态不佳，请重试", type:'showToast'})
            }else{
							resolve(res.data)
						}
          }).catch(error => {
            // console.log('wxRequesterror', error)
          })
        } else {
          wx.cloud.callContainer({
            path: url.indexOf('?') == -1 ? url + '?' + encodeSearchParams(data) : url + '&' + encodeSearchParams(data), // 透传到后台服务
            header: headers,
            method: 'GET'
          }).then((res) => {
            if (show_loading) {
              tip.loaded();
              clearTimeout(loadTime)
            }
            if (url.indexOf('cloud-sales-order/customer/sales_order') !== -1 && params.method == 'POST') {
              if (res.statusCode == 500 || res.statusCode == 504) {
                uni.redirectTo({
                  url: '/pages/util/error'
                });
              }
            }
            if (res.statusCode == 429) {
              // tip.plainText('您动作太快，请慢点哟～', 2000)
							resolve({msg: "您动作太快，请慢点哟～", type:'showToast'})
            }else if (res && res.errMsg == "request:fail timeout") {
              // tip.plainText('网络状态不佳，请重试')
							resolve({msg: "网络状态不佳，请重试", type:'showToast'})
            }else{
							resolve(res.data)
						}
          }).catch(error => {
            // console.log('wxRequesterror', error)
          })
        }
      } else {
        let res = await uni.request({
          url: baseUrlRequest + serviceUrl + path,
          method: params.method || 'GET',
          data: data,
          timeout: 100000,
          header: {
            'Content-Type': 'application/json',
            ...headers
          }
        });
        if (show_loading) {
          tip.loaded();
          clearTimeout(loadTime)
        }

        if (url.indexOf('cloud-sales-order/customer/sales_order') !== -1 && params.method == 'POST') {
          if (res[1].statusCode == 500 || res[1].statusCode == 504) {
            uni.redirectTo({
              url: '/pages/util/error'
            });
          }
        }
        if(res[1].statusCode == 429) {
          // tip.plainText('您动作太快，请慢点哟～',2000)
					resolve({msg: "您动作太快，请慢点哟～", type:'showToast'})
        }else if (res[1] && res[1].errMsg == "request:fail timeout") {
          // tip.plainText('网络状态不佳，请重试')
					resolve({msg: '网络状态不佳，请重试', type:'showToast'})
        }else{
					resolve(res[1].data)
				}
      }
    }
  })

};
const wxRequestGoodsList = async (params = {}, baseUrl, serviceUrl, apiKey, path, show_loading = false) => {
  return new Promise(async (resolve, reject) => {
    const baseUrlRequest = accountInfo.miniProgram.envVersion == 'release' || api.environment == "formal" ? "https://api.cloud.efashionchina.com" : "https://macallan.morefun.me"
    // let url = baseUrlRequest + serviceUrl + path
     let host = baseUrlRequest.substring(8)
    let url = serviceUrl + path
    if (show_loading) {
      tip.loading();
    }
    let data = params.query || {};
    let headers = params.header || {};
    if (!!apiKey) {
      headers['X-Api-Key'] = apiKey
    }
    headers['appId'] = appId
    if(api.environment == "formal") {
      headers['X-WX-EXCLUDE-CREDENTIALS'] = 'unionid, cloudbase-access-token, openid'
      headers['X-WX-GATEWAY-ID'] = GATEWAYIDJSON[api.environment]
      headers['HOST'] = host
      if (url.search('efashionchina') === -1) {
        data.sign = SIGN;
        data.time = TIMESTAMP;
      }
      wx.cloud.callContainer({
        path: url, // 透传到后台服务
        header: headers,
        method: params.method || 'GET',
        data: data,
      }).then((res) => {
        if (res && res.statusCode == 429) {
          // tip.plainText('您动作太快，请慢点哟～', 2000)
					resolve({msg: "您动作太快，请慢点哟～", type:'showToast'})
        }else if (show_loading) {
          tip.loaded();
					resolve(res.data)
        }else{
					resolve(res.data)
				}
      }).catch(error => {
        // console.log('wxRequestGoodsListerror', error)
      })
    } else {
      let res = await uni.request({
        url: baseUrlRequest + serviceUrl + path,
        method: params.method || 'GET',
        data: data,
        timeout: 100000,
        header: {
          'Content-Type': 'application/json',
          ...headers
        }
      });
      if (show_loading) {
        tip.loaded();
        clearTimeout(loadTime)
      }

      if (url.indexOf('cloud-sales-order/customer/sales_order') !== -1 && params.method == 'POST') {
        if (res[1].statusCode == 500 || res[1].statusCode == 504) {
          uni.redirectTo({
            url: '/pages/util/error'
          });
        }
      }
      if(res[1].statusCode == 429) {
        // tip.plainText('您动作太快，请慢点哟～',2000)
				resolve({msg: "您动作太快，请慢点哟～", type:'showToast'})
      }else if (res[1] && res[1].errMsg == "request:fail timeout") {
        // tip.plainText('网络状态不佳，请重试')
				resolve({msg: "网络状态不佳，请重试", type:'showToast'})
      }else{
				resolve(res[1].data)
			}
    }

  })
};
const wxRequestWithJwt = async (params = {}, baseUrl, serviceUrl, apiKey, path, show_loading = false) => {
  return new Promise(async (resolve, reject) => {
    const baseUrlRequest = accountInfo.miniProgram.envVersion == 'release' || api.environment == "formal" ? "https://api.cloud.efashionchina.com" : "https://macallan.morefun.me"
    let url = serviceUrl + path;
    let host = baseUrlRequest.substring(8)
    if (url != '') {
      clearTimeout(loadTime)
      if (show_loading) {
        loadTime = setTimeout(() => {
          tip.loading();
        }, 500)
      }
      let data = params.query || {};
      let headers = params.header || {};
      if (Object.keys(headers).length > 0 && !headers.jwt) {
        let settingRes = await uni.getSetting();
        if (settingRes[1]?.authSetting['scope.userInfo']) {
          if (!!uni.getStorageSync("customerInfo") && !!uni.getStorageSync("customerInfo").jwt) {
            headers = {
              jwt: uni.getStorageSync("customerInfo").jwt || getApp().globalData.customerInfo.jwt
            }
          } else {
          }
        } else {
          // console.log('未授权无法获取jwt')
        }
      }
      if (!!apiKey) {
        headers['X-Api-Key'] = apiKey
      }
      headers['appId'] = appId
      if(api.environment == "formal") {
        headers['X-WX-EXCLUDE-CREDENTIALS'] = 'unionid, cloudbase-access-token, openid'
        headers['X-WX-GATEWAY-ID'] = GATEWAYIDJSON[api.environment]
        headers['HOST'] = host
        if (url.search('efashionchina') === -1) {
          data.sign = SIGN;
          data.time = TIMESTAMP;
        }
        wx.cloud.callContainer({
          path: url, // 透传到后台服务
          header: headers,
          method: params.method || 'GET',
          data: data,
        }).then((res) => {
          if (show_loading) {
            tip.loaded();
            clearTimeout(loadTime)
          }
          if (url.indexOf('cloud-sales-order/customer/sales_order') !== -1 && params.method == 'POST') {
            if (res.statusCode == 500 || res.statusCode == 504) {
              uni.redirectTo({
                url: '/pages/util/error'
              });
            }
          }
          if (res && res.statusCode == 429) {
            // tip.plainText('您动作太快，请慢点哟～', 2000)
						resolve({msg: "您动作太快，请慢点哟～", type:'showToast'})
          }else if (res && res.errMsg == "request:fail timeout") {
            // tip.plainText('网络状态不佳，请重试')
						resolve({msg: "您动作太快，请慢点哟～", type:'showToast'})
          }else{
						resolve(res.data)
					}
        }).catch(error => {
          // console.log('wxRequestWithJwterror', error)
        })
      } else {
        let res = await uni.request({
          url: baseUrlRequest + serviceUrl + path,
          method: params.method || 'GET',
          data: data,
          timeout: 100000,
          header: {
            'Content-Type': 'application/json',
            ...headers
          }
        });
        if (show_loading) {
          tip.loaded();
          clearTimeout(loadTime)
        }

        if (url.indexOf('cloud-sales-order/customer/sales_order') !== -1 && params.method == 'POST') {
          if (res[1].statusCode == 500 || res[1].statusCode == 504) {
            uni.redirectTo({
              url: '/pages/util/error'
            });
          }
        }
        if(res[1].statusCode == 429) {
          // tip.plainText('您动作太快，请慢点哟～',2000)
					resolve({msg: "您动作太快，请慢点哟～", type:'showToast'})
        }else if (res[1] && res[1].errMsg == "request:fail timeout") {
          // tip.plainText('网络状态不佳，请重试')
					resolve({msg: "网络状态不佳，请重试", type:'showToast'})
        }else{
					resolve(res[1].data)
				}
      }

    }
  })
};
const wxRequestWithTime = async (params = {}, baseUrl, serviceUrl, apiKey, path, show_loading = false) => {
  return new Promise(async (resolve, reject) => {
    const baseUrlRequest = accountInfo.miniProgram.envVersion == 'release' || api.environment == "formal" ? "https://api.cloud.efashionchina.com" : "https://macallan.morefun.me"
    let host = baseUrlRequest.substring(8)
    let url = serviceUrl + path
    if (url != '') {
      clearTimeout(loadTime)
      if (show_loading) {
        loadTime = setTimeout(() => {
          tip.loading();
        }, 500)
      }
      let data = params.query || {};
      let headers = params.header || {};
      if (!!apiKey) {
        headers['X-Api-Key'] = apiKey
      }
      headers['appId'] = appId
      if(api.environment == "formal") {
        headers['X-WX-EXCLUDE-CREDENTIALS'] = 'unionid, cloudbase-access-token, openid'
        headers['X-WX-GATEWAY-ID'] = GATEWAYIDJSON[api.environment]
        headers['HOST'] = host
        if (url.search('efashionchina') === -1) {
          data.sign = SIGN;
          data.time = TIMESTAMP;
        }
        if(!!params.method && params.method != "GET") {
          wx.cloud.callContainer({
            path: url, // 透传到后台服务
            header: headers,
            method: params.method || 'GET',
            data: data,
          }).then((res) => {
            if (show_loading) {
              tip.loaded();
              clearTimeout(loadTime)
            }
            if (url.indexOf('cloud-sales-order/customer/sales_order') !== -1 && params.method == 'POST') {
              if (res.statusCode == 500 || res.statusCode == 504) {
                uni.redirectTo({
                  url: '/pages/util/error'
                });
              }
            }
            if (res.statusCode == 429) {
              // tip.plainText('您动作太快，请慢点哟～', 2000)
							resolve({msg: "您动作太快，请慢点哟～", type:'showToast'})
            }else if (res && res.errMsg == "request:fail timeout") {
              // tip.plainText('网络状态不佳，请重试')
							resolve({msg: "网络状态不佳，请重试", type:'showToast'})
            }else{
							resolve(res)
						}
          }).catch(error => {
            // console.log('wxRequesterror', error)
          })
        } else {
          wx.cloud.callContainer({
            path: url.indexOf('?') == -1 ? url + '?' + encodeSearchParams(data) : url + '&' + encodeSearchParams(data), // 透传到后台服务
            header: headers,
            method: 'GET'
          }).then((res) => {
            if (show_loading) {
              tip.loaded();
              clearTimeout(loadTime)
            }
            if (url.indexOf('cloud-sales-order/customer/sales_order') !== -1 && params.method == 'POST') {
              if (res.statusCode == 500 || res.statusCode == 504) {
                uni.redirectTo({
                  url: '/pages/util/error'
                });
              }
            }
            if (res.statusCode == 429) {
              // tip.plainText('您动作太快，请慢点哟～', 2000)
							resolve({msg: "您动作太快，请慢点哟～", type:'showToast'})
            }else if (res && res.errMsg == "request:fail timeout") {
              // tip.plainText('网络状态不佳，请重试')
							resolve({msg: "网络状态不佳，请重试", type:'showToast'})
            }else{
							resolve(res)
						}
          }).catch(error => {
            // console.log('wxRequesterror', error)
          })
        }
      } else {
        let res = await uni.request({
          url: baseUrlRequest + serviceUrl + path,
          method: params.method || 'GET',
          data: data,
          timeout: 100000,
          header: {
            'Content-Type': 'application/json',
            ...headers
          }
        });
        if (show_loading) {
          tip.loaded();
          clearTimeout(loadTime)
        }

        if (url.indexOf('cloud-sales-order/customer/sales_order') !== -1 && params.method == 'POST') {
          if (res[1].statusCode == 500 || res[1].statusCode == 504) {
            uni.redirectTo({
              url: '/pages/util/error'
            });
          }
        }
        if(res[1].statusCode == 429) {
          // tip.plainText('您动作太快，请慢点哟～',2000)
					resolve({msg: "您动作太快，请慢点哟～", type:'showToast'})
        }else if (res[1] && res[1].errMsg == "request:fail timeout") {
          // tip.plainText('网络状态不佳，请重试')
					resolve({msg: "网络状态不佳，请重试", type:'showToast'})
        }else{
					resolve(res[1])
				}
      }

    }
  })
};

module.exports = {
  wxRequest,
  wxRequestWithJwt,
  wxRequestGoodsList,
  wxRequestWithTime
};
